package com.swak.persistence.mybatis.methods.impls;

import com.swak.define.ColumnDefine;
import com.swak.persistence.mybatis.methods.Sqls;
import com.swak.utils.StringUtils;

/**
 * 插入
 * 
 * @author lifeng
 * @date 2021年1月22日 上午9:10:32
 */
public class Insertive extends BatchInsert {

	@Override
	protected void doInject() {
		if (!this.supportMethod(Sqls.INSERTIVE)) {
			return;
		}

		String sql = new StringBuilder().append(SCRIPT_START).append(this.withIgnoreInsertFlagHintClause())
				.append(SPACE).append(this.table.getName()).append(LEFT_BRACKET).append(this.parseInsertSqlColumns())
				.append(RIGHT_BRACKET).append(SPACE).append(VALUES).append(LEFT_BRACKET)
				.append(this.parseInsertSqlProperty()).append(RIGHT_BRACKET).append(SCRIPT_END).toString();

		this.addInsertMappedStatement(this.table.entity, Sqls.INSERTIVE.getMethod(), sql);
	}

	protected String withIgnoreInsertFlagHintClause() {
		return StringUtils.format(
				"<if test=\" %s != null and %s != null \">%s</if><if test=\" %s == null or %s == null \">%s</if>", Hint,
				Hint_IgnoreInsertFlag, INSERT_IGNORE, Hint, Hint_IgnoreInsertFlag, INSERT);
	}

	/**
	 * 解析列
	 */
	protected String parseInsertSqlColumns() {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : table.columns) {
			if (column.isVersion()) {
				sql.append(column.name).append(SPLIT);
			} else if (!column.isPk() && !column.isCreateDate() && !column.isUpdateDate() && !column.isDel()) {
				sql.append("<if test=\"").append(column.javaProperty).append(" != null\">");
				sql.append(column.name).append(SPLIT);
				sql.append("</if>");
			} else {
				sql.append(column.name).append(SPLIT);
			}
		}
		if (table.define.useLogicDel()) {
			sql.append(DEL_AT);
		} else {
			sql.delete(sql.lastIndexOf(SPLIT), sql.length() - 1);
		}
		return sql.toString();
	}

	/**
	 * insert 后面的属性值
	 * 
	 * @param <T>
	 * @param table
	 * @return
	 */
	protected String parseInsertSqlProperty() {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : table.columns) {
			if (column.isVersion()) {
				sql.append("1").append(SPLIT);
			} else if (!column.isPk() && !column.isCreateDate() && !column.isUpdateDate() && !column.isDel()) {
				sql.append("<if test=\"").append(column.javaProperty).append(" != null\">");
				sql.append(HASH_LEFT_BRACE).append(column.javaPropertyEl).append(RIGHT_BRACE).append(SPLIT);
				sql.append("</if>");
			} else {
				sql.append(HASH_LEFT_BRACE).append(column.javaPropertyEl).append(RIGHT_BRACE).append(SPLIT);
			}
		}
		if (table.define.useLogicDel()) {
			sql.append(HASH_LEFT_BRACE).append(delAtProperty).append(RIGHT_BRACE);
		} else {
			sql.delete(sql.lastIndexOf(SPLIT), sql.length() - 1);
		}
		return sql.toString();
	}
}